package com.syz.web.controller;

import com.syz.web.pojo.User;
import com.syz.web.pojo.query.UserQuery;
import com.syz.web.service.IUserService;

import com.syz.web.service.Impl.UserServiceImpl;
import com.syz.web.util.JSONUtil;
import com.syz.web.util.LayUITableResult;
import com.syz.web.util.PageInfo;
import com.syz.web.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private IUserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //req.setCharacterEncoding("UTF-8");

        String method = req.getParameter("method");
        if (method == null || method.equals("")) {
            method = "selectByPage";
        }
        switch (method) {
            case "selectByPage":
                selectByPage(req, resp);
                break;
            case "deleteById":
                deleteById(req, resp);
                break;
            case "deleteAll":
                deleteAll(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "getUserUpdatePage":
                getUserUpdatePage(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req,resp);
                break;
        }
    }
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.logout");

        HttpSession session = req.getSession();
        session.invalidate();
        resp.sendRedirect(req.getContextPath() );
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.login");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {

            JSONUtil.toJSON(resp, Result.error("验证码错误"));
            return;
        }

        User user = userService.login(name, password );
        if (user != null) {
            //把user作为登录凭证放到Session，
            //后面只要判断Session里面有没有user，就知道当前这个用户有没有登录
            session.setAttribute("user", user);

            JSONUtil.toJSON(resp, Result.ok("登录成功"));
        } else {
            JSONUtil.toJSON(resp, Result.error("用户名或密码错误"));
        }
    }
    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.update");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        User user = new User(Integer.parseInt(id), name, password, Integer.parseInt(age), gender);
        boolean isSuccess = userService.update(user);
        //resp.sendRedirect(req.getContextPath() + "/user");
        Result result = isSuccess ? Result.ok("修改成功") : Result.error("修改失败");
        JSONUtil.toJSON(resp, result);
    }

    private void getUserUpdatePage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("UserServlet.getUserUpdatePage");
        String id = req.getParameter("id");
        User user = userService.selectById(Integer.parseInt(id));
        req.setAttribute("user", user);
        req.getRequestDispatcher("User/user_update.jsp").forward(req, resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.add");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        User user = new User(name, password, Integer.parseInt(age), gender);
        System.err.println(user);
        boolean isSuccess = userService.add(user);
        //resp.sendRedirect(req.getContextPath() + "/user");
        if(isSuccess){
            JSONUtil.toJSON(resp,Result.ok("添加成功"));
        }else{
            JSONUtil.toJSON(resp,Result.error("添加失败"));
        }
    }

    private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.deleteById");
        String id = req.getParameter("id");
        boolean isSuccess = userService.deleteById(Integer.parseInt(id));
        if(isSuccess){
            JSONUtil.toJSON(resp,Result.ok());
        }else{
            JSONUtil.toJSON(resp,Result.error());
        }

        //resp.sendRedirect(req.getContextPath() + "/user");
    }
    private void deleteAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.deleteAll");
        //String id = req.getParameter("id");
        String[] ids = req.getParameterValues("ids[]");
        boolean isSuccess = userService.deleteAll(ids);

        Result result = isSuccess ? Result.ok("删除成功") : Result.error("删除失败");
        JSONUtil.toJSON(resp, result);
    }
    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("UserServlet.selectByPage");
        String pageStr = req.getParameter("page");
        if (pageStr == null || pageStr.equals("")) {
            pageStr = "1";
        }
        String limitStr = req.getParameter("limit");
        if (limitStr == null || limitStr.equals("")) {
            limitStr = "10";
        }
        int page = Integer.parseInt(pageStr);
        int limit = Integer.parseInt(limitStr);
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        UserQuery userQuery = new UserQuery(page, limit, name, gender);

        LayUITableResult layUITableResult = userService.selectByPage(userQuery);
        System.out.println("LayUITableResult: " + layUITableResult);

        JSONUtil.toJSON(resp, layUITableResult);
    }
    // /user?method=selectByPage&pageNo=2&pageSize=5
//    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("UserServlet.selectByPage");
//        String pageNoStr = req.getParameter("pageNo");
//        if (pageNoStr == null || pageNoStr.equals("")) {
//            pageNoStr = "1";
//        }
//        String pageSizeStr = req.getParameter("pageSize");
//        if (pageSizeStr == null || pageSizeStr.equals("")) {
//            pageSizeStr = "5";
//        }
//        int pageNo = Integer.parseInt(pageNoStr);
//        int pageSize = Integer.parseInt(pageSizeStr);
//
//        PageInfo<User> pageInfo = userService.selectByPage(pageNo, pageSize);
//        System.out.println("pageInfo: " + pageInfo);
//
//        req.setAttribute("pageInfo", pageInfo);
//        req.getRequestDispatcher("User/user_list.jsp").forward(req, resp);
//    }
}
